import React, { useState } from 'react';
import {
  Typography,
  Box,
  Button,
  TextField,
  Grid,
  Card,
  CardContent,
  CircularProgress,
} from '@mui/material';
import { DIDDocument } from '../types/api';
import { API_CONFIG } from '../config';
import { ApiService } from '../services/api';

interface DIDSectionProps {
  node: keyof typeof API_CONFIG.NODES;
}

export const DIDSection: React.FC<DIDSectionProps> = ({ node }) => {
  const [did, setDid] = useState<string>('');
  const [pubKeyId, setPubKeyId] = useState('');
  const [didDocument, setDidDocument] = useState<DIDDocument | null>(null);
  const [publicKey, setPublicKey] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<DIDDocument | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!did) {
      setError('请输入DID标识符');
      return;
    }

    try {
      setLoading(true);
      setError(null);
      setResult(null);

      console.log('Querying DID:', did);
      const response = await ApiService.getDIDDocument(node, did);
      console.log('DID response:', response);
      
      if (response && response.result) {
        setResult(response.result);
        setDidDocument(response.result);
      } else {
        setError(`查询失败: ${response?.message || '未找到DID文档'}`);
      }
    } catch (err) {
      setError(`查询DID文档失败: ${err instanceof Error ? err.message : '未知错误'}`);
      console.error('Error fetching DID document:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleGetPublicKey = async () => {
    if (!pubKeyId) {
      setError('Please enter a public key ID');
      return;
    }

    setLoading(true);
    try {
      if (!didDocument) {
        setError('请先查询 DID 文档');
        setLoading(false);
        return;
      }
      const key = didDocument.publicKeys.find(k => k.id === pubKeyId);
      if (key) {
        setPublicKey(key.publicKeyHex);
        setError('');
      } else {
        setError('未找到对应公钥');
        setPublicKey(null);
      }
    } catch (err) {
      setError(`获取公钥失败: ${err instanceof Error ? err.message : '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box>
      <Typography variant="h5" gutterBottom>
        DID 管理
      </Typography>

      <Grid container spacing={2}>
        <Grid item xs={12}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                查询 DID 文档
              </Typography>
              <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <label htmlFor="did" className="block text-sm font-medium text-gray-700">
                    DID标识符
                  </label>
                  <input
                    type="text"
                    id="did"
                    value={did}
                    onChange={(e) => setDid(e.target.value)}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                    placeholder="请输入DID标识符..."
                  />
                </div>
                <button
                  type="submit"
                  disabled={loading}
                  className="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  {loading ? '查询中...' : '查询DID文档'}
                </button>
              </form>

              {error && (
                <div className="mt-4 text-red-500 bg-red-50 p-4 rounded-md">
                  <p className="font-medium">错误:</p>
                  <p>{error}</p>
                </div>
              )}

              {result && (
                <Box>
                  <Typography variant="subtitle1" gutterBottom>
                    DID 文档详情：
                  </Typography>
                  <pre style={{ overflow: 'auto' }}>
                    {JSON.stringify(result, null, 2)}
                  </pre>
                </Box>
              )}
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                查询公钥
              </Typography>
              <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
                <TextField
                  label="公钥 ID"
                  value={pubKeyId}
                  onChange={(e) => setPubKeyId(e.target.value)}
                  fullWidth
                />
                <Button
                  variant="contained"
                  onClick={handleGetPublicKey}
                  disabled={loading}
                >
                  {loading ? <CircularProgress size={24} /> : '查询'}
                </Button>
              </Box>

              {error && (
                <Typography color="error" sx={{ mb: 2 }}>
                  {error}
                </Typography>
              )}

              {publicKey && (
                <Box>
                  <Typography variant="subtitle1" gutterBottom>
                    Public Key:
                  </Typography>
                  <pre style={{ overflow: 'auto' }}>
                    {publicKey}
                  </pre>
                </Box>
              )}
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  );
};

export default DIDSection; 